package gods.bubble.server;

import gods.bubble.common.StandardDocument;
import gods.bubble.search.SearchResult;
import gods.bubble.search.Searcher;
import gods.bubble.util.Config;

import java.io.IOException;

import org.apache.lucene.search.highlight.InvalidTokenOffsetsException;

public class SearchService {
	private Searcher s = null;

	public SearchService() {
		try {
			s = new Searcher(Config.indexDir, Config.scholarIndexDir);
		} catch (Exception e) {
			System.out.println("Can't init Searcher.");
			e.printStackTrace();
		}
	}

	public String search(String query, int offset, int length, int type) {
		try {
			StringBuilder sb = new StringBuilder();
			SearchResult result = s
					.search(query, offset, length, type);

			for (StandardDocument sr : result.hits) {
				sb.append(sr.toHtml());
			}
			
			sb.append("#HITSNUMBER#" + result.totalHits);

			//System.out.println(sb.toString());
			
			return sb.toString();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static void main(String args[]) throws IOException,
			InvalidTokenOffsetsException {
		SearchService s = new SearchService();

		s.search("清华新闻", 0, 10, Searcher.Type.ALL);
	}
}
